import os


def add_line_to_specify_place():
    with open("/Users/ddy/py/test/test_lines.txt", "r") as file:
        old = file.readlines()
        print(old)
    lines = len(old)
    with open("/Users/ddy/py/test/test_lines.txt", "w") as file:
        file.write(str(lines) + " SSSS\n")
        # for item in old:
        file.writelines(old)
    with open ("/Users/ddy/py/test/test_lines.txt", "r") as file:
        file_content = file.read()
        print(file_content)


if __name__ == '__main__':
    add_line_to_specify_place()


def test():
    file = "/Users/ddy/py/test/socket_test-simple.txt"

    '''
    w 以写方式打开，
    a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
    r+ 以读写模式打开
    w+ 以读写模式打开 (参见 w ) 重新打开会覆盖原有内容
    a+ 以读写模式打开 (参见 a ) 不会覆盖文件内容
    rb 以二进制读模式打开
    wb 以二进制写模式打开 (参见 w )
    ab 以二进制追加模式打开 (参见 a )
    rb+ 以二进制读写模式打开 (参见 r+ )
    wb+ 以二进制读写模式打开 (参见 w+ )
    ab+ 以二进制读写模式打开 (参见 a+ )
    '''
    # w: 如果不存在就新建文件,每次写入会覆盖之前的旧内容
    # w+: 追加写入方式打开文件,重新打开会覆盖之前的旧内容
    # *** 读写完后要关闭！！！
    f = open(file, 'w')
    if os.path.exists(file):
        f.write("1234 567 890\n")
        f.writelines("writelines")  # writelines 自动添加换行
    else:
        print("file is not exist")

    f.close()
    f_r = open(file, 'r')  # 默认模式，可以不带参数'r'
    print(f_r.read())
    f_r.close()

    f_w_plus = open(file, 'w+')
    f_w_plus.write("I'm a w+\n")
    f_w_plus.close()

    f_r_p = open(file, 'r')
    print(f_r_p.read())
    f_r_p.close()
    '''
    f_r_p.readline()  # 读一行
    f_r_p.readlines()  # 读取所有行
    f.writelines(list[1, 2, 3])  # 同时写入多行
    f.read(1)  # 每次读取一个字符
    '''

    os.chdir("/Users/ddy/py/test")
    #
    f_range_w = open("test_range_w.txt", "a+")
    for i in range(10):
        print(i)
        f_range_w.write("times: {}. ".format(i))
    f_range_w.write("\n")
    f_range_w.close()


    with open("test_range_w.txt", 'a+') as with_file:
        with_file.writelines("ha ha! this is open file with 'with'.")

    with open("test_range_w.txt", 'r') as with_file:
        print("read", with_file.readline())
